/*============================================================================
 * Copyright 2009 VMware Inc.
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 
 * use this file except in compliance with the License. You may obtain a copy 
 * of the License at: http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
 * License for the specific language governing permissions and limitations 
 * under the License.
 ============================================================================*/

package com.vmware.vcloud;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.vmware.vcloud.data.VAppStatus;
import com.vmware.vcloud.data.XmlBuilder;
import com.vmware.vcloud.rest.RestClient;

/**
 * @author Steve Jin (sjin@vmware.com)
 */

public class VApp extends VCloudObject
{
	
	public VApp(RestClient rc, String href) throws MalformedURLException
	{
		super(rc, href);
	}
	
	public VApp(RestClient rc, String href, String name) throws MalformedURLException
	{
		super(rc, href, name);
	}
	
	protected void parse()
	{
		//TODO
	}
	
	public String getIpAddress() throws IOException
	{
		loadContentIfNotYet();
		List<?> sectionList = root.elements("Section");
		
		for(int i=0; i<sectionList.size(); i++)
		{
			Element section = (Element) sectionList.get(i);
			if("q1:NetworkConnectionSectionType".equals(section.attributeValue("type")))
			{
				return section.element("NetworkConnection").elementText("IpAddress");
			}
		}
		
		return null;
	}
	
	public void rename(String newName) throws IOException
	{
		loadContentIfNotYet();
		
		String reqBody = XmlBuilder.buildVAppRenameReq(getURL(), newName, root.attributeValue("status"), root.attributeValue("size"));
		rc.put(getURL(), reqBody, "application/vnd.vmware.vcloud.vApp+xml");
	}
	
	public Task powerOn() throws IOException
	{
		System.out.println("poweron url:" + getURL() + "/power/action/powerOn");
		String taskUrl = rc.post(getURL() + "/power/action/powerOn");
		System.out.println("taskUrl:" + taskUrl);
		System.out.println(rc.get(taskUrl));
		return new Task(rc, taskUrl);
	}
	
	public Task powerOff() throws IOException
	{
		String taskUrl = rc.post(getURL() + "/power/action/powerOff");
		return new Task(rc, taskUrl);
	}
	
	public Task reset() throws IOException
	{
		String taskUrl = rc.post(getURL() + "/power/action/reset");
		return new Task(rc, taskUrl);
	}
	
	public Task shutdown() throws IOException
	{
		String taskUrl = rc.post(getURL() + "/power/action/shutdown");
		return new Task(rc, taskUrl);
	}

	/**
	 * Get the status of the vApp
	 * @return
	 * 0 -- Being created
	 * 2 -- Off
	 * 4 -- Powered on
	 * @throws IOException 
	 * @throws MalformedURLException 
	 * @throws Exception
	 */
	public VAppStatus getStatus() throws IOException
	{
		String res = rc.get(getURL());
		try
		{
		Document doc = DocumentHelper.parseText(res);
		String status = doc.getRootElement().attributeValue("status");
		return VAppStatus.getFromValue(status);
		} 
		catch(DocumentException de)
		{
			throw new RuntimeException(de);
		}
	}
	
	public void waitFor(VAppStatus targetStatus) throws IOException, InterruptedException
	{
		waitFor(targetStatus, 2000);
	}
	
	public void waitFor(VAppStatus targetStatus, int intervalInMillSecond) throws IOException, InterruptedException
	{
		for(;;)
		{
			VAppStatus status = getStatus();
			System.out.println("status:" + status +":" + getURL());
			System.out.println("targetStatus:" + targetStatus);
			if(targetStatus==status)
			{
				return;
			}
			Thread.sleep(intervalInMillSecond);
		}
	}
	
	public void delete() throws IOException, InterruptedException
	{
		// vApp can be deleted ONLY when it's powered off
		if(getStatus()==VAppStatus.running)
		{
			powerOff();
			waitFor(VAppStatus.poweredoff);
		}
		rc.delete(getURL());
	}
}